package com.yu1996.stack;

public class LinkedStackDemo {

    public static void main(String[] args) {
        LinkedStack linkedStack = new LinkedStack();
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
//        linkedStack.list();
        linkedStack.push(node1);
        linkedStack.list();
    }
}


class LinkedStack {
    private Node temper = new Node(-1);
    private Node top = temper;

    public boolean isEmpty() {
        return top == temper;
    }

    public void push(Node node) {
        top.setNext(node);
        top = top.getNext();
    }

    public Node pop() {
        if (isEmpty()) {
            throw new RuntimeException("链表为空，无法出栈");
        }
        //定义辅助节点
        Node temp = temper;
        //遍历到最后一个节点的前一位
        while (temp.getNext() != top) {
            temp = temp.getNext();
        }
        //出栈
        top = temp;
        return top;
    }

    public void list() {
        if (isEmpty()) {
            System.out.println("链表为空~");
            return;
        }
        //定义辅助节点遍历
        Node temp = temper;
        while (temp.getNext() != null) {
            int i = 1;
            System.out.printf("第%d个节点是:%d\n", i, temp.getNo());
            i++;
        }
    }

}

class Node {
    private int no; //编号
    private Node next;

    public Node(int no) {
        this.no = no;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                '}';
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}